package com.jlnk.petdemo.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.jlnk.petdemo.R;
import com.jlnk.petdemo.entity.PetModel;
import com.jlnk.petdemo.view.PetDetailActivity;

import java.util.List;

public class PetAdapter extends RecyclerView.Adapter<PetAdapter.PetViewHolder> {
    private final List<PetModel> petList;

    public PetAdapter(List<PetModel> petList) {
        this.petList = petList;
    }

    @NonNull
    @Override
    public PetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pet, parent, false);
        return new PetViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PetViewHolder holder, int position) {
        PetModel pet = petList.get(position);
        holder.nameTextView.setText(pet.getName());
        Glide.with(holder.itemView.getContext()).load(pet.getCoverURL()).into(holder.imageView);
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(v.getContext(), PetDetailActivity.class);
            intent.putExtra("PET_DETAIL", pet);
            v.getContext().startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return petList.size();
    }

    public void updatePetList(List<PetModel> newPetList) {
        if (newPetList != null) {
            petList.clear();
            petList.addAll(newPetList);
            notifyDataSetChanged();
        } else {
            petList.clear();
            notifyDataSetChanged();
        }
    }

    static class PetViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView nameTextView;

        public PetViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image);
            nameTextView = itemView.findViewById(R.id.name);
        }
    }
}